package com.miniserver.util;

import java.io.File;
import java.util.List;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.HierarchicalConfiguration;
import org.apache.commons.configuration.XMLConfiguration;
import org.apache.commons.configuration.tree.xpath.XPathExpressionEngine;

/**
 * 从 /web-inf/props/configuration.xml中获取配置信息
 * 
 */
public class AppConfiguration {
	static LogUtil log = LogUtil.getLogUtil("AppConfiguration");
	static Object lockObj = new Object();
	private static Configuration config = null;
	private static String webRootName = null;

	/**
	 * 取系统根路径
	 * @return
	 */
	public static String getBaseFolder(){
		return System.getProperty(getWebRootName());
	}
	
	/**
	 * 获取webRootName
	 * 
	 * @return
	 */
	public static String getWebRootName() {
		return webRootName;
	}

	/**
	 * 设置webRootName
	 * 
	 * @param webRootName
	 */
	public static void setWebRootName(String webRootName) {		
		AppConfiguration.webRootName = webRootName;
		if (config == null) {
			config = unmarshall();
		}
	}

	/**
	 * 获取imageCacheAddresses连接地址
	 * 
	 * @return
	 */
	public static String getImageCacheAddressesString() {
		List<?> imageCacheAddress = config.getList("imageCacheAddresses");
		StringBuffer buffer = new StringBuffer();
		for (Object val : imageCacheAddress) {
			buffer.append(val).append(" ");
		}
		buffer.setLength(buffer.length() - 1);
		return buffer.toString();
	}

	/**
	 * 获取xml配置文件指定名称的结果集
	 * 
	 * @param parameter
	 * @return
	 */
	public static List<?> getList(String parameter) {
		return config.getList(parameter);
	}

	/**
	 * 获取xml配置文件指定名称的结果
	 * 
	 * @param name
	 * @return
	 */
	public static String getParameter(String name) {
		try
		{
			return config.getString(name);
		}
		catch(Exception ex)
		{
			log.error(ex);
		}
		return null;
	}

	/**
	 * Marshals the configuration from XML document
	 */
	private static Configuration unmarshall() {
		File destFile = null;
		try {
			String basePath = System.getProperty(webRootName);
			File sourceFile =  new File(basePath, "WEB-INF/props/configuration.xmlbin");
			destFile = new File(basePath, "WEB-INF/props/configuration.xml");
			DKeyDesEncrypt.decryptFile(sourceFile, destFile);			
			Configuration config = new XMLConfiguration(destFile.getAbsolutePath());
			((HierarchicalConfiguration) config).setExpressionEngine(new XPathExpressionEngine());
			return config;
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		finally
		{
			if (destFile!=null &&destFile.exists())
			{
				destFile.delete();			
			}
		}
		return null;
	}
}
